<template>
  <div class="wechat-auth">
    <el-card class="auth-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">微信授权</span>
        </div>
      </template>

      <div class="auth-content">
        <!-- 授权状态显示 -->
        <div class="status-section">
          <div class="status" :class="authStatus">
            <el-icon v-if="authStatus === 'loading'" class="spinner">
              <Loading />
            </el-icon>
            <el-icon v-else-if="authStatus === 'success'" class="success-icon">
              <Check />
            </el-icon>
            <el-icon v-else-if="authStatus === 'error'" class="error-icon">
              <Close />
            </el-icon>
            <span class="status-text">{{ statusMessage }}</span>
          </div>
        </div>

        <!-- 授权成功显示用户信息 -->
        <div v-if="authStatus === 'success'" class="user-info-section">
          <div class="user-info">
            <h4>授权成功</h4>
            <div class="openid-display">
              <span class="label">OpenID:</span>
              <span class="value">{{ userInfo.openid }}</span>
              <el-button type="text" @click="copyOpenId" size="small">复制</el-button>
            </div>

            <div v-if="userInfo.nickname" class="user-details">
              <div class="user-detail-item">
                <span class="label">昵称:</span>
                <span class="value">{{ userInfo.nickname }}</span>
              </div>
              <div class="user-detail-item">
                <span class="label">性别:</span>
                <span class="value">{{ getGenderText(userInfo.sex) }}</span>
              </div>
              <div class="user-detail-item">
                <span class="label">地区:</span>
                <span class="value">{{ getUserLocation(userInfo) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 错误信息显示 -->
        <div v-if="authStatus === 'error'" class="error-section">
          <div class="error-message">{{ errorMessage }}</div>
          <div class="retry-actions">
            <el-button type="primary" @click="retryAuth">重新授权</el-button>
            <el-button @click="manualAuth">手动授权</el-button>
          </div>
        </div>

        <!-- 授权按钮 -->
        <div v-if="!authStatus || authStatus === 'error'" class="auth-actions">
          <el-button type="primary" size="large" @click="initiateAuth" :loading="isLoading" class="auth-button">
            <el-icon>
              <ChatDotRound />
            </el-icon>
            微信授权登录
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed,defineProps, withDefaults,defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Check, Close, ChatDotRound } from '@element-plus/icons-vue'
import { loginBgWeChatApi } from '~/composables/useLeasedFactory'
import type { TokenBase } from '~/types/api'

interface Props {
  appid?: string
  scope?: string
  serverUrl?: string
}

interface Emits {
  (e: 'auth-success', data: any): void
  (e: 'auth-error', error: string): void
}
const props = withDefaults(defineProps<Props>(), {
  appid: 'wx1252cf1f26c7faee',
  scope: 'snsapi_base',
  serverUrl: () => process.client ? window.location.origin : ''
})

const emit = defineEmits<Emits>()

// 统一错误提示
const showErrorMsg = (msg: string) => ElMessage.error(msg || "请求失败，请重试")

// 状态管理
const authStatus = ref<'loading' | 'success' | 'error' | null>(null)
const statusMessage = ref('')
const errorMessage = ref('')
const userInfo = ref<any>({})

// 计算属性
const isLoading = computed(() => authStatus.value === 'loading')

// 检查URL参数
const route = useRoute()
const code = route.query.code as string
const state = route.query.state as string

onMounted(() => {
  console.log('微信授权组件初始化')
  console.log('当前URL:', process.client ? window.location.href : '')
  console.log('URL参数:', route.query)

  // 检查是否配置了appid
  if (props.appid === 'YOUR_APPID_HERE') {
    showErrorMsg('请先配置您的微信公众号appid')
    return
  }

  // 根据是否有code参数决定流程
  if (!code) {
    console.log('未检测到code参数，等待用户点击授权')
    showStatus('请点击下方按钮进行微信授权', 'info')
  } else {
    console.log('检测到code参数:', code)
    showStatus('正在获取用户信息...', 'loading')
    getOpenId(code)
  }
})

// 发起微信授权
const initiateAuth = () => {
  showStatus('正在跳转到微信授权页面...', 'loading')

  // 构造回调URL，指向微信回调页面
  const currentUrl = new URL(process.client ? window.location.href : '')
  const qybh = currentUrl.searchParams.get('QYBH') || '65ad7a5723244a13a1703c134b1bb627'
  const qymc = currentUrl.searchParams.get('QYMC') || '相城光辉芯片制造有限公司'

  const redirectUri = encodeURIComponent(
    `${process.client ? window.location.origin : ''}/ezsafe-visitor/wechat-callback?qybh=${qybh}&qymc=${encodeURIComponent(qymc)}`
  )

  // 构造微信授权URL
  const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${props.appid}&redirect_uri=${redirectUri}&response_type=code&scope=${props.scope}&state=wechat_auth#wechat_redirect`

  // 3秒后跳转到微信授权页面
  if (process.client) {
    setTimeout(() => {
      window.location.href = authUrl
    }, 3000)
  }
}

// 使用code换取openid
const getOpenId = async (code: string) => {
  try {
    showStatus('正在获取openid...', 'loading')

    // 调用后端API获取openid
    const res = await loginBgWeChatApi({ code: code }, true)
    if (res.code !== '0') {
      showErrorMsg('登录失败')
      return
    }
    const { result } = res as { result: TokenBase }
    console.log('获取openid结果:', result.openid)
    if (result.openid) {
      userInfo.value = result
      showSuccess(result)
      emit('auth-success', result)
    } else {
      throw new Error(res.message || '获取openid失败')
    }
  } catch (error: any) {
    console.error('获取openid失败:', error)
    showError(`获取openid失败: ${error.message}`)
    emit('auth-error', error.message)
  }
}

// 获取用户详细信息
const getUserInfo = async () => {
  try {
    if (!userInfo.value.access_token || !userInfo.value.openid) {
      throw new Error('缺少必要的认证信息')
    }

    showStatus('正在获取用户信息...', 'loading')

    // 调用后端API获取用户信息
    const response = await fetch(
      `${props.serverUrl}/api/getUserInfo?access_token=${encodeURIComponent(
        userInfo.value.access_token
      )}&openid=${encodeURIComponent(userInfo.value.openid)}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      }
    )

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(
        `HTTP error! status: ${response.status}, message: ${errorText}`
      )
    }

    const data = await response.json()
    console.log('获取用户信息结果:', data)

    if (data.userInfo) {
      userInfo.value = { ...userInfo.value, ...data.userInfo }
      showStatus('用户信息获取成功！', 'success')
    } else {
      throw new Error(data.error || '获取用户信息失败')
    }
  } catch (error: any) {
    console.error('获取用户信息失败:', error)
    showError(`获取用户信息失败: ${error.message}`)
  }
}

// 显示成功状态
const showSuccess = (data: any) => {
  authStatus.value = 'success'
  statusMessage.value = '授权成功！'
  errorMessage.value = ''
}

// 显示错误状态
const showError = (message: string) => {
  authStatus.value = 'error'
  statusMessage.value = '授权失败'
  errorMessage.value = message
}

// 显示状态信息
const showStatus = (message: string, type: 'loading' | 'success' | 'error' | 'info') => {
  if (type === 'info') {
    authStatus.value = null
  } else {
    authStatus.value = type
  }
  statusMessage.value = message
}

// 重新授权
const retryAuth = () => {
  showStatus('正在重新发起授权...', 'loading')
  setTimeout(() => {
    initiateAuth()
  }, 1000)
}

// 手动授权
const manualAuth = () => {
  if (process.client) {
    const code = prompt('请输入微信授权返回的code参数：')
    if (code) {
      showStatus('正在处理手动输入的code...', 'loading')
      getOpenId(code)
    }
  }
}

// 复制OpenID
const copyOpenId = () => {
  if (!userInfo.value.openid) {
    ElMessage.error('没有可复制的OpenID')
    return
  }

  if (process.client && navigator.clipboard) {
    navigator.clipboard
      .writeText(userInfo.value.openid)
      .then(() => {
        ElMessage.success('OpenID已复制到剪贴板')
      })
      .catch((err) => {
        console.error('复制失败:', err)
        ElMessage.error('复制失败，请手动选择复制')
      })
  }
}

// 获取性别文本
const getGenderText = (sex: number) => {
  const genderMap = { 0: '未知', 1: '男', 2: '女' }
  return genderMap[sex as keyof typeof genderMap] || '未知'
}

// 获取用户地区信息
const getUserLocation = (user: any) => {
  const location = [user.country, user.province, user.city]
    .filter((item) => item)
    .join(' - ')
  return location || '未知'
}
</script>

<style scoped>
.wechat-auth {
  margin-bottom: 2rem;
}

.auth-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #303133;
}

.auth-content {
  text-align: center;
}

.status-section {
  margin-bottom: 2rem;
}

.status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.status.loading {
  background: #e3f2fd;
  color: #1976d2;
}

.status.success {
  background: #e8f5e8;
  color: #2e7d32;
}

.status.error {
  background: #ffebee;
  color: #c62828;
}

.spinner {
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.success-icon {
  margin-right: 10px;
  color: #67c23a;
}

.error-icon {
  margin-right: 10px;
  color: #f56c6c;
}

.status-text {
  font-size: 16px;
}

.user-info-section {
  margin: 2rem 0;
  text-align: left;
}

.user-info h4 {
  color: #303133;
  margin-bottom: 1rem;
  text-align: center;
}

.openid-display {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
  margin: 15px 0;
  word-break: break-all;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #eee;
}

.openid-display .label {
  font-weight: bold;
  margin-right: 10px;
}

.openid-display .value {
  flex: 1;
  margin-right: 10px;
}

.user-details {
  margin-top: 1rem;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.user-detail-item {
  margin: 8px 0;
  display: flex;
}

.user-detail-item .label {
  font-weight: bold;
  width: 80px;
  flex-shrink: 0;
}

.user-detail-item .value {
  flex: 1;
}

.error-section {
  margin: 2rem 0;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 1rem;
  padding: 15px;
  background: #ffebee;
  border-radius: 8px;
}

.retry-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.auth-actions {
  margin: 2rem 0;
}

.auth-button {
  min-width: 200px;
  height: 50px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .openid-display {
    flex-direction: column;
    align-items: flex-start;
  }

  .openid-display .value {
    margin: 10px 0;
    word-break: break-all;
  }

  .retry-actions {
    flex-direction: column;
  }

  .auth-button {
    width: 100%;
  }
}
</style>
